#pragma once
#include <iostream>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "log.hpp"
#include "common.hpp"
#include "inetAddr.hpp"

using namespace LogModule;

const static int default_fd = -1;
const static int default_listen_wait = -1;
class Socket
{
public:
    virtual void SocketOper() = 0;
    virtual void BindOper(InetAddr &addr) = 0;
    virtual void ListenOper() = 0;
    virtual std::shared_ptr<Socket> AcceptOper(InetAddr &addr) = 0;
    virtual void Close() = 0;

public:
    void BuiltUdpSocket(InetAddr &addr)
    {
        SocketOper();
        BindOper(addr);
        ListenOper();
    }
};

class UdpSocket : public Socket
{
public:
    UdpSocket(int fd = default_fd)
        : _fd(fd)
    {
    }

    void SocketOper() override
    {
        _fd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_fd < 0)
        {
            LOG((int)LogLevel::FATAL) << "套接字创建失败！";
            exit(SOCKET_ERR);
        }
        LOG((int)LogLevel::INFO) << "Udp套接字创建成功！";
    }

    void BindOper(InetAddr &addr) override
    {
        int n = ::bind(_fd, addr.Sockaddr(), addr.Socklen());
        if (n < 0)
        {
            LOG((int)LogLevel::FATAL) << "bind失败！";
            exit(BIND_ERR);
        }
        LOG((int)LogLevel::INFO) << "bind成功！";
    }

    void ListenOper() override
    {
        int n = ::listen(_fd, default_listen_wait);
        if (n < 0)
        {
            LOG((int)LogLevel::FATAL) << "listen失败！";
            exit(BIND_ERR);
        }
        LOG((int)LogLevel::INFO) << "listen成功！";
    }

    std::shared_ptr<Socket> AcceptOper(InetAddr &addr) override
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int n = accept(_fd, (sockaddr *)&peer, &len);
        if (n < 0)
        {
            LOG((int)LogLevel::FATAL) << "accept失败！";
            exit(ACCEPT_ERR);
        }
        LOG((int)LogLevel::INFO) << "accept成功！";
        addr.SetInetAddr(peer);
        return std::make_unique<UdpSocket>(_fd);
    }

    void Close() override
    {
        if(_fd > 0)
        {
            ::close(_fd);
        }
    }

private:
    int _fd;
};